<template>
  <div class="app-container">

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 第一行: 预约时间和就诊科室 -->
        <el-row :gutter="20">
          <!-- 第一行: 预约时间和就诊卡号 -->
          <el-col :span="12">
            <el-form-item label="预约时间" prop="registTime">
              <el-date-picker
                clearable
                v-model="form.registTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择预约时间"
                :picker-options="pickerOptions0"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="就诊卡号" prop="clinicCard" >
              <el-input v-model="form.clinicCard" style="width: 220px" placeholder="请输入就诊卡号"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="就诊科室" prop="departmentId">
              <el-select v-model="form.departmentId" placeholder="请选择科室">
                <el-option v-for="item in departmentList" :key="item.id" :label="item.name" :value="item.id">
                  {{ item.name }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="就诊医生" prop="doctorId">
              <el-select v-model="form.doctorId" placeholder="请选择医生">
                <el-option v-for="item in doctorList" :key="item.id" :label="item.name" :value="item.id" v-if="item.departmentId == form.departmentId">
                  {{ item.name }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行: 就诊姓名和就诊性别 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name" >
              <el-input v-model="form.name" style="width: 220px" placeholder="请输入姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.value">{{
                    dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行: 身份证号和就诊年龄 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="identityCard">
              <el-input v-model="form.identityCard" style="width: 220px" placeholder="请输入身份证号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age"  controls-position="right" :min="0" :max="150" style="width: 220px;"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行: 手机号码和所属民族 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" style="width: 220px" placeholder="请输入手机号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属民族" prop="nation">
              <el-select v-model="form.nation" placeholder="请选择所属民族" clearable>
                <el-option
                  v-for="dict in dict.type.people_ethnic_ffiliation"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>

        <!-- 第六行: 联系地址 -->
        <el-form-item label="联系地址" prop="address">
          <el-input v-model="form.address" style="width: 420px" placeholder="请输入联系地址"/>
        </el-form-item>
        <el-form-item label="预约渠道" prop="appointmentWay">
          <el-radio-group v-model="form.appointmentWay">
            <el-radio v-for="dict in dict.type.user_channel_status" :key="dict.value" :label="dict.value">
              {{dict.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <image-upload v-model="form.img"/>
        </el-form-item>

        <!-- 第七行: 门诊编号和住院编号 -->
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门诊编号" prop="outpatientId">
              <el-input v-model="form.outpatientId" style="width: 220px" placeholder="请输入门诊编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="住院编号" prop="admissionId">
              <el-input v-model="form.admissionId" style="width: 220px" placeholder="请输入住院编号"/>
            </el-form-item>
          </el-col>
        </el-row> -->

        <!-- 第八行: 医保性质和医保卡号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医保性质" prop="nature">
              <!-- <el-input v-model="form.nature"  style="width: 220px" placeholder="请输入医保性质"/> -->
              <el-radio-group v-model="form.nature">
            <el-radio v-for="dict in dict.type.patient_medical_status" :key="dict.value" :label="dict.value">
              {{dict.label}}
            </el-radio>

          </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="医保卡号" prop="cardnumber">
              <el-input v-model="form.cardnumber" style="width: 220px" placeholder="请输入医保卡号"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="submitForm">保存挂号</el-button>
      </div>
  </div>
</template>

<script>
import {listYuyue, getYuyue, delYuyue, addYuyue, updateYuyue, getDepartmentList,getDoctorList,addCost,addConsultation } from "@/api/register/add";

export default {
  name: "Yuyue",
  dicts: ['people_ethnic_ffiliation', 'user_channel_status', 'sys_yes_no', 'sys_user_sex','patient_medical_status'],
  data() {
    return {
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      doctorList:[],
      departmentList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约表格数据
      yuyueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 预约医生时间范围
      daterangeRegistTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        registTime: null,
        name: null,
        phone: null,
        isCancel: null,
        appointmentWay: null,
        departmentId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        registTime: [
          { required: true, message: "预约时间不能为空", trigger: "blur" }
        ],
        department: [
          { required: true, message: "就诊科室不能为空", trigger: "change" }
        ],
        doctorId: [
          { required: true, message: "就诊医生不能为空", trigger: "change" }
        ],
        clinicCard: [
          {required: true, message: "就诊卡号不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "姓名不能为空", trigger: "blur"}
        ],
        identityCard: [
          {required: true, message: "身份证号不能为空", trigger: "blur"}
        ],
        age: [
          {required: true, message: "年龄不能为空", trigger: "blur"}
        ],
        sex: [
          {required: true, message: "性别不能为空", trigger: "change"}
        ],
        phone: [
          {required: true, message: "手机号码不能为空", trigger: "blur"}
        ],
        nation: [
          {required: true, message: "民族不能为空", trigger: "change"}
        ],
        address: [
          {required: true, message: "联系地址不能为空", trigger: "blur"}
        ],
        appointmentWay: [
          {required: true, message: "预约渠道不能为空", trigger: "change"}
        ],
        departmentId: [
          {required: true, message: "预约科室不能为空", trigger: "change"}
        ],
      }
    };
  },
  created() {
    this.getDepartmentList();
    this.getDoctorList();
  },
  methods: {
    disabledDate(date) {
      return date < new Date().setHours(0, 0, 0, 0); // 禁止选择今天之前的日期
    },
    getDoctorList() {
      getDoctorList().then(response => {
        this.doctorList = response.rows;
      })
    },
    getDepartmentList() {
      getDepartmentList().then(response => {
        this.departmentList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        registStatus: null,
        registTime: null,
        clinicCard: null,
        name: null,
        identityCard: null,
        age: null,
        sex: null,
        img: null,
        phone: null,
        nation: null,
        address: null,
        outpatientId: null,
        medicalhistory: null,
        admissionId: null,
        nature: null,
        cardnumber: null,
        isCancel: null,
        medicalFee: null,
        appointmentWay: null,
        departmentId: null,
        doctorId: null,
        del: null
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预约";
      this.getDepartmentList();
      this.getDoctorList();
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getYuyue(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预约";
        this.getDepartmentList();
        this.getDoctorList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 更新操作
            updateYuyue(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();  // 更新列表
            }).catch(error => {
              console.error("更新预约失败:", error);
            });
          } else {
            const selectedDepartment = this.departmentList.find(
              dept => dept.id == this.form.departmentId
            );

            if (selectedDepartment) {
              this.form.money = selectedDepartment.money; // 将科室对应的 money 赋值到表单
            }
            // 新增操作
            addYuyue(this.form).then(response => {
              const patientId = response.data.id;  // 使用后端返回的 ID
              const registTime = this.form.registTime;
              const money = this.form.money;
              console.log(money);
              // 新增费用数据
              const costData = {
                costType: 0,
                auditStatus: 0,
                costNum: `COST-${Date.now()}`,
                patientId: patientId,
                costStatus: 1,
                money: money,
                create_time: registTime,
              };
              // 新增费用
              addCost(costData).finally(() => {
                this.$modal.msgSuccess("新增成功");
                location.reload();
                this.reset();
              }).catch(error => {
                console.error("新增费用失败:", error);
              });
            }).catch(error => {
              console.error("新增预约失败:", error);
            });
          }
        }
      });
    },
  }
};
</script>
